package com.javafactroy.kunlong.base.dto;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.javafactroy.kunlong.client.feign.dto.PageInfoDto;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.List;

@Data
@Accessors(chain = true)
public class TQueryParam<T extends PageInfoDto> {

    @JsonInclude(JsonInclude.Include.NON_NULL)

    Integer start;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    Integer limit;
    String orderBys;
    @JsonInclude(JsonInclude.Include.NON_NULL)

    Integer pageSize;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    Integer pageNum;


    protected T param;

    public T toParam() {

        if (start == null) {
            start = 0;
        }
        if (limit == null) {
            limit = 10;
        }

        param.setPageNum(start / limit + 1);
        param.setPageSize(limit);
        if (pageNum != null) {
            param.setPageNum(pageNum);

        }
        if (pageSize != null) {
            param.setPageSize(pageSize);
        }
        if (ObjectUtil.isNotEmpty(orderBys)) {
            List<String> list = StrUtil.split(orderBys, "|");
            if (list.size() < 2) {
                list.add("asc");
            }
            param.orderBy(list.get(0), list.get(1));
        }
        return param;
    }

    public T fetchParamIfNull() {
        if (param != null) {
            return param;
        }
        return null;
    }
}
